// 导入数据库API
const db = require('../../config/db');
// 导入生成id的包
const { v4: uuidv4 } = require('uuid');
// 操作数据库的业务
module.exports = {
    // 示例：
    test() {
        return new Promise((resolve, reject) => { })
    },
    // 发布题库
    add(topic_lib_name, topic_count, topic_single_count, topic_multi_count, topic_judge_count, exam_time, exam_type, topic_lib_id, user_id, exam_limit, exam_fullcredit, exam_passline) {
        return new Promise((resolve, reject) => {
            let sql = `insert into db_topic_lib(topic_lib_name,topic_count,topic_single_count,topic_multi_count,topic_judge_count,exam_time,exam_type,topic_lib_id,user_id,exam_limit,exam_fullcredit,exam_passline) values("${topic_lib_name}","${topic_count}","${topic_single_count}","${topic_multi_count}","${topic_judge_count}","${exam_time}","${exam_type}","${topic_lib_id}","${user_id}","${exam_limit}","${exam_fullcredit}","${exam_passline}")`;
            db.query(sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: '发布题库失败。'
                    })
                } else {
                    resolve({
                        code: 200,
                        msg: '发布题库成功。'
                    })
                }
            })
        })
    },

    // 删除题库（用户自己删除）
    remove(topic_lib_id, user_id) {
        return new Promise((resolve, reject) => {
            let sql = `delete from  db_topic_lib where topic_lib_id = "${topic_lib_id}" and user_id="${user_id}"`
            db.query(sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: '删除题库失败。'
                    })
                } else {
                    let check_exam_sql = `select exam_name from db_exam where topic_lib_id = "${topic_lib_id}"`;
                    db.query(check_exam_sql, (emsg, arr) => {
                        if (emsg) {
                            reject({ code: -1, msg: '删除题库失败。' })
                        } else {
                            if (arr.length == 0) {
                                resolve({ code: 200, msg: '删除题库成功。' })
                            } else {
                                // 与题库对应的考试记录、题目表记录都删除
                                let del_exam_sql = `delete from  db_exam where topic_lib_id = "${topic_lib_id}"`
                                let del_topic_sql = `delete from  db_topic where topic_lib_id = "${topic_lib_id}"`
                                db.query(del_exam_sql, (error2, rows2) => {
                                    if (error2) { reject({ code: -1, msg: '删除考试失败。' }) } else { }
                                });
                                db.query(del_topic_sql, (error3, rows3) => {
                                    if (error3) { reject({ code: -1, msg: '删除考试失败。' }) } else { resolve({ code: 200, msg: '删除题库(考试)成功。' }) }
                                });
                            }
                        }
                    })
                }
            });
        })
    },

    // 删除题库（管理员删除）
    delete(topic_lib_id) {
        return new Promise((resolve, reject) => {
            let sql = `delete from  db_topic_lib where topic_lib_id = "${topic_lib_id}"`
            db.query(sql, (err, rows) => {
                if (err) {
                    reject({
                        code: -1,
                        msg: '删除题库失败。'
                    })
                } else {
                    let check_exam_sql = `select exam_name from db_exam where topic_lib_id = "${topic_lib_id}"`;
                    db.query(check_exam_sql, (emsg, arr) => {
                        if (emsg) {
                            reject({ code: -1, msg: '删除题库失败。' })
                        } else {
                            if (arr.length == 0) {
                                resolve({ code: 200, msg: '删除题库成功。' })
                            } else {
                                // 与题库对应的考试记录、题目表记录都删除
                                let del_exam_sql = `delete from  db_exam where topic_lib_id = "${topic_lib_id}"`
                                let del_topic_sql = `delete from  db_topic where topic_lib_id = "${topic_lib_id}"`
                                db.query(del_exam_sql, (error2, rows2) => {
                                    if (error2) { reject({ code: -1, msg: '删除考试失败。' }) } else { }
                                });
                                db.query(del_topic_sql, (error3, rows3) => {
                                    if (error3) { reject({ code: -1, msg: '删除考试失败。' }) } else { resolve({ code: 200, msg: '删除题库(考试)成功。' }) }
                                });
                            }
                        }
                    })
                }
            });
        })
    },

    // 题库列表（管理员）
    list(page_num, page_size) {
        return new Promise((resolve, reject) => {
            let startIndex = (page_num - 1) * page_size;
            let len = page_size;
            let sql = `select * from db_topic_lib limit ${startIndex},${len}`;
            db.query(sql, (err, rows) => {
                // console.log({err})
                if (err) {
                    resolve({
                        code: -1,
                        msg: '获取题库列表失败。',
                        err
                    })
                } else {

                    resolve({
                        code: 200,
                        msg: "获取题库列表成功。",
                        result: rows,
                        page: {
                            page_num: page_num,
                            page_size: page_size,
                        }
                    })
                }
            })
        })

    },

    list2(user_id) {
        return new Promise((resolve, reject) => {
            let sql = `select * from db_topic_lib where user_id = "${user_id}"`;
            db.query(sql, (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '获取题库列表失败。',
                        err
                    })
                } else {
                    resolve({
                        code: 200,
                        msg: "获取题库列表成功。",
                        result: rows
                    })
                }
            })
        })

    },
    // 题库列表（用户）
    list3(page_num, page_size, user_id) {
        // console.log(page_num, page_size,user_id)
        return new Promise((resolve, reject) => {
            let startIndex = (page_num - 1) * page_size;
            let len = page_size;
            let sql = `select * from db_topic_lib where user_id="${user_id}" limit ${startIndex},${len}`;
            db.query(sql, (err, rows) => {
                // console.log({err})
                if (err) {
                    resolve({
                        code: -1,
                        msg: '获取题库列表失败。',
                        err
                    })
                } else {
                    resolve({
                        code: 200,
                        msg: "获取题库列表成功。",
                        result: rows,
                        page: {
                            page_num: page_num,
                            page_size: page_size,
                        }
                    })
                }
            })
        })

    },

    // 题库详情
    detail(topic_lib_id) {
        return new Promise((resolve, reject) => {
            let sql = `select * from db_topic_lib where topic_lib_id="${topic_lib_id}"`;
            db.query(sql, (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '查询题库列表失败。',
                        err
                    })
                } else {
                    resolve({
                        code: 200,
                        msg: "查询题库详情成功。",
                        result: rows
                    })
                }
            })
        })
    },

    // 搜索题库
    // 参数：keyword
    search(keyword) {
        return new Promise((resolve, reject) => {
            let sql = "select * from db_topic_lib where topic_lib_name LIKE CONCAT('%" + keyword + "%') or exam_type LIKE CONCAT('%" + keyword + "%')";
            db.query(sql, (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '查询题库信息失败。',
                        err
                    })
                } else {
                    if (rows.length == 0) {
                        resolve({
                            code: -1,
                            msg: '没有该关键字匹配题库信息。'
                        })
                    } else {
                        resolve({
                            code: 200,
                            msg: '查询题库信息成功。',
                            result: rows
                        })
                    }
                }
            })
        })
    },

    // 统计题库数量（管理员）
    total2() {
        return new Promise((resolve, reject) => {
            db.query('select count(*) as total from db_topic_lib', (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '统计题库数量失败。',
                        err
                    })
                } else {
                    resolve({
                        code: 200,
                        msg: "获取题库数量成功。",
                        total: rows[0]['total']
                    })
                }
            })

        })
    },
    // 统计题库数量（用户）
    total(user_id) {
        return new Promise((resolve, reject) => {
            db.query(`select topic_lib_name from db_topic_lib where user_id = "${user_id}"`, (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '统计题库数量失败。',
                        err
                    })
                } else {
                    resolve({
                        code: 200,
                        msg: "获取题库数量成功。",
                        result: rows
                    })
                }
            })

        })
    },
    // 发布题库(考试)
    publish(topic_lib_id) {
        return new Promise((resolve, reject) => {
            let update_topiclib_sql = `update db_topic_lib set topic_ispublish = "1"  where  topic_lib_id = "${topic_lib_id}"`;
            db.query(update_topiclib_sql, function (err, rows) {
                if (err) {
                    reject({ code: -1, msg: "发布题库失败" });
                } else {
                    let check_topiclib_sql = `select * from db_topic_lib where topic_lib_id="${topic_lib_id}"`;
                    db.query(check_topiclib_sql, (error, result) => {
                        if (error) {
                            reject({ code: -1, msg: "添加到试卷失败1" })
                        } else {
                            // 当题库发布时、会在db_exam表中记录
                            if (result.length != 0) {

                                let { topic_lib_name, exam_limit, exam_time, exam_type, exam_fullcredit, exam_passline, topic_lib_id } = result[0];

                                let exam_id = uuidv4();

                                let insert_exam_sql = `insert into db_exam(exam_id,exam_name,exam_limit,exam_time,exam_type,exam_fullcredit,exam_passline,topic_lib_id) values("${exam_id}","${topic_lib_name}","${exam_limit}","${exam_time}","${exam_type}","${exam_fullcredit}","${exam_passline}","${topic_lib_id}")`;

                                db.query(insert_exam_sql, (err2, rows2) => {
                                    if (err2) {
                                        reject({ code: -1, msg: "发布题库(考试信息)失败" })
                                    } else {
                                        resolve({ code: 200, msg: "发布题库(考试信息)成功。" });
                                    }
                                })
                            } else {
                                reject({ code: -1, msg: "添加到试卷失败2" })
                            }
                        }
                    })

                }
            });
        })
    },

    // 获取已发布题库
    get_publish(user_id) {
        return new Promise((resolve, reject) => {
            let sql = `select * from db_topic_lib where  topic_ispublish = "1" and user_id = "${user_id}"`;
            // console.log({ user_id })
            db.query(sql, function (err, rows) {
                // console.log({ err })
                if (err) {
                    reject({ code: -1, msg: "获取题库失败。" });
                } else {
                    resolve({ code: 200, msg: "获取已题库成功。", result: rows });
                }
            });
        })
    },

}